package com.eningqu.aipen.ui.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.graphics.drawable.Animatable;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.ObservableBoolean;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eningqu.aipen.MyApplication;
import com.eningqu.aipen.demo.PenCtrlSdkManager;
import com.eningqu.aipen.demo.R;
import com.eningqu.aipen.demo.activity.SDKMainActivity;
import com.eningqu.aipen.demo.databinding.FragmentHomeBinding;
import com.eningqu.aipen.logic.model.medical.GhTodayBean;
import com.eningqu.aipen.logic.network.Apis;
import com.eningqu.aipen.logic.network.BaseRetrofitUtils;
import com.eningqu.aipen.logic.network.RxLifecycle;
import com.eningqu.aipen.logic.network.SchedulerTransformer;
import com.eningqu.aipen.sdk.ErrorCode;
import com.eningqu.aipen.sdk.NQPenSDK;
import com.eningqu.aipen.sdk.bean.device.NQBtDevice;
import com.eningqu.aipen.sdk.bean.device.NQDeviceBase;
import com.eningqu.aipen.sdk.comm.ConnectState;
import com.eningqu.aipen.sdk.comm.ScanListener;
import com.eningqu.aipen.sdk.listener.PenConnectListener;
import com.eningqu.aipen.sdk.listener.PenMsgListener;
import com.eningqu.aipen.ui.adapter.WorkAdapter;
import com.eningqu.aipen.ui.base.BaseFragment;
import com.eningqu.aipen.utils.GlobalConfig;
import com.eningqu.aipen.utils.PopTipUtils;
import com.eningqu.aipen.utils.SPUtil;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

@SuppressWarnings("unused")
public class HomeFragment extends BaseFragment<FragmentHomeBinding> {

    private RefreshLayout refresh;
    private WorkAdapter adapter;
    private RxPermissions rxPermission;
    private final List<GhTodayBean.GhListDTO> list = new ArrayList<>();

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);



        intiPenSDK();
        isBluetoothAvailable();
        //动态获取权限
        rxPermission = new RxPermissions(requireActivity());
        requestPermissions();
        mBinding.setOnClick(new MainClick());
        mBinding.setIsConnect(isConnect);


        RecyclerView recyclerView = mBinding.listWork;
        adapter = new WorkAdapter(list, isConnect);
        LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(manager);
        PagerSnapHelper helper = new PagerSnapHelper();
        helper.attachToRecyclerView(recyclerView);

        recyclerView.setAdapter(adapter);
        refresh = mBinding.smartRefresh;
        refresh.setOnRefreshListener(refreshLayout -> {
            refresh.finishRefresh(2000);
            async();
        });
        refresh.setEnableLoadMore(false);//关闭加载更多
        refresh.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onHeaderStartAnimator(RefreshHeader header, int footerHeight, int maxDragHeight) {
                super.onHeaderStartAnimator(header, footerHeight, maxDragHeight);
                if (mBinding.header.getDrawable() instanceof Animatable) {
                    ((Animatable) mBinding.header.getDrawable()).start();
                }
            }

            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {
                super.onHeaderFinish(header, success);
                if (mBinding.header.getDrawable() instanceof Animatable) {
                    ((Animatable) mBinding.header.getDrawable()).stop();
                }
            }
        });

        mBinding.btTest.setOnClickListener(v -> {
            if (MyApplication.isConnect == 1) {
                mBinding.btTest.setText("测试按钮：模拟连接点阵笔");
                MyApplication.isConnect = -1;
                isConnect.set(false);
            } else {
                mBinding.btTest.setText("测试按钮：模拟连接断开");
                MyApplication.isConnect = 1;
                isConnect.set(true);
            }
        });

        initGuideDialog();
    }

    /**
     * 动态权限
     */
    @SuppressLint("CheckResult")
    private void requestPermissions() {
        rxPermission.request(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
//                        isCancelPermission = true;
//                        //完成授权
//                        //开始扫描蓝牙设备，自动连接
//                        if (!isCancelBtEnable) {
//                            openBluetoothAndLocation(SDKMainActivity.this);
//                        }
                } else {
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if(GlobalConfig.isDeBug){
            mBinding.btTest.setVisibility(View.VISIBLE);
        }else{
            mBinding.btTest.setVisibility(View.GONE);
        }
    }

    public void initGuideDialog() {
        CustomDialog.show(new OnBindView<CustomDialog>(R.layout.dialog_guide) {

                    private TextView tvConfirm;

                    @Override
                    public void onBind(final CustomDialog dialog, View v) {
                        tvConfirm = v.findViewById(R.id.tvConfirm);
                        tvConfirm.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                    }
                })
                .setCancelable(false)
                .setMaskColor(getResources().getColor(R.color.black30))
                .setAlignBaseViewGravity(mBinding.clickConnect, Gravity.START | Gravity.CENTER_VERTICAL)
                .show();
    }


    public static final String TAG = "MainActivity";
    ArrayList<NQDeviceBase> mDeviceLists = new ArrayList<>();

    ObservableBoolean isConnect = new ObservableBoolean(false);

    private static final int REQUEST_ENABLE_BT = 2;//蓝牙权限
    private static final int REQUEST_PERMISSION_LOCATION = 4;//定位权限


    private BluetoothAdapter mBtAdapter = null;

    /**
     * 扫描监听
     */
    ScanListener mScanListener = new ScanListener() {
        @Override
        public void onScanStart() {

            mDeviceLists.clear();
            LogUtils.i("扫描监听 onScanStart: 开始");

        }

        @Override
        public void onScanStop() {

            LogUtils.i("onScanStop: 停止");
        }

        @Override
        public void onReceiveException(int error, String message) {
            LogUtils.e("扫描监听 结果异常 error=" + error + ", message=" + message);
        }

        @Override
        public void onScanResult(final NQDeviceBase device) {

            LogUtils.i("扫描结果 onScanResult: device" + device.exInfo);
            //搜索到一个设备
            addDevice(device);
        }
    };

    @Override
    protected void async() {
        Integer ysId = (Integer) SPUtil.getInstance().getData(GlobalConfig.ysId, -1);
        Apis apis = BaseRetrofitUtils.getInstance().create(Apis.class);
        if (ysId == -1) {
            PopTip.tip("请先登录，默认账号密码是····");
        } else {
            Disposable d = BaseRetrofitUtils.getInstance().create(Apis.class).getTodayGh(ysId)
                    .compose(new SchedulerTransformer<>())
                    .compose(RxLifecycle.bindExLifecycle(this))
                    .subscribe(bean -> {
                        if (bean != null) {
                            list.clear();
                            list.addAll(bean.ghList);
                            adapter.notifyDataSetChanged();
                            adapter.notifyItemInserted(list.size() - 1);
                            if (list.size() == 0) {
                                PopTip.tip("暂无数据");
                                mBinding.ivEmpty.setVisibility(View.VISIBLE);
                                mBinding.tvEmpty.setVisibility(View.VISIBLE);
                            } else {
                                mBinding.ivEmpty.setVisibility(View.GONE);
                                mBinding.tvEmpty.setVisibility(View.GONE);
                            }
                        }
                    });
        }
    }

    @Override
    protected void initStatusBar() {

    }


    @SuppressWarnings("all")
    public class MainClick {
        public void clickConnect(View view) {
            showConnectDialog();
        }


        public void goToSdkMain(View view) {
            if (MyApplication.isConnect == -1) {
                PopTip.tip("请先连接智能点阵笔....");
            } else {
                PopTip.tip("这是sdk原生界面，测试功能专用");
                SDKMainActivity.startAction(getContext());
            }
        }


    }


    ListFragmentDialog patientDialog;

    private void showPatientDialog() {

        Bundle bundle = new Bundle();
        bundle.putString("tv_title", "选择就诊的患者");
        bundle.putString("tv_fresh", "下拉刷新");
        if (patientDialog == null) {
            patientDialog = new ListFragmentDialog();
            patientDialog.setArguments(bundle);
            patientDialog.show(getFragmentManager(), "patient_dialog");
            patientDialog.setOnSelectListener(new ListFragmentDialog.SelectListener() {
                @Override
                public void Select(NQDeviceBase deviceBase) {

                }

                @Override
                public void freshDevice() {

                }
            });
        } else {
            patientDialog.setArguments(bundle);
            patientDialog.show(getFragmentManager(), "patient_dialog");
        }

    }

    /**
     * 初始化笔SDK
     */
    private void intiPenSDK() {
        //sdk管理单例到初始化，PenCtrlSdkManager是智能笔SDK管理单例，对sdk进行二次封装
        PenCtrlSdkManager.getInstance().init(requireContext().getApplicationContext(), NQPenSDK.CONN_TYPE.BLE);
        //添加监听器
        setPenListener();
        //开始搜索
        PenCtrlSdkManager.getInstance().startScanDevice();
    }

    /**
     * 设置各类事件监听
     */
    private void setPenListener() {
        //设置扫描回调
        PenCtrlSdkManager.getInstance().setScanListener(mScanListener);
        //设置连接监听
        PenCtrlSdkManager.getInstance().setConnectListener(connectListener);
        //设置笔信息监听
        PenCtrlSdkManager.getInstance().setPenMsgListener(penMsgListener);
    }

    /**
     * 连接回调
     */
    PenConnectListener connectListener = new PenConnectListener() {
        @Override
        public void onConnectState(int i) {
            if (i == ConnectState.CONN_STATE_CONNECTED) {
                isConnect.set(true);
                MyApplication.isConnect = 1;
                PopTipUtils.successMsg("连接成功");
            } else if (i == ConnectState.CONN_STATE_CONNECTING) {
                ToastUtils.showLong("连接回调 连接中... state=" + i);
            } else if (i == ConnectState.CONN_STATE_DISCONNECTING) {
                ToastUtils.showLong("连接回调 断开连接中... state=" + i);
                isConnect.set(false);
                MyApplication.isConnect = -1;
            } else if (i == ConnectState.CONN_STATE_CLOSED) {
                ToastUtils.showLong("连接回调 连接断开... state=" + i);
                isConnect.set(false);
                MyApplication.isConnect = -1;
            }
        }

        @Override
        public void onUsbDeviceAttached(UsbDevice usbDevice) {
            LogUtils.i("usb device attached...");
        }

        @Override
        public void onUsbDeviceDetached(UsbDevice usbDevice) {
            LogUtils.i("usb device detached...");
        }

        @Override
        public void onReceiveException(int i, String s) {
            LogUtils.e("receiveException error=" + i + ", message=" + s);
            mDeviceLists.clear();
            PenCtrlSdkManager.getInstance().release();
            if (i == ErrorCode.ERR_CONN_CONNECT) {
                ToastUtils.showLong("onReceiveException 连接断开... error=" + i);
                isConnect.set(false);
                MyApplication.isConnect = -1;
            }
        }
    };

    /**
     * 笔的信息
     */
    PenMsgListener penMsgListener = new PenMsgListener() {
        @Override
        public void onEditName(String s) {

        }

        @Override
        public void bleVersion(String s) {

        }

        @Override
        public void onFWVer(String s) {
            PopTip.tip("固件版本：" + s);
        }

        @Override
        public void onMCUVer(String s) {
            PopTip.tip("MCU版本：" + s);
        }

        @Override
        public void onBatInfo(float v) {
            PopTip.tip("电压：" + v);
        }

        @Override
        public void onFlashUsedAmount(int i) {

        }

        @Override
        public void onSerialNumber(String s) {
            //序列号
            PopTip.tip("序列号：" + s);
        }
    };


    /**
     * 检查设备是否支持蓝牙
     */
    private void isBluetoothAvailable() {
        // 检查蓝牙适配器
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
            PopTip.tip("设备不支持蓝牙");
            return;
        }
        //检查蓝牙权限
        checkStartConditions();
    }

    /**
     * 蓝牙设备检查启动的条件，usb不需要
     */
    private void checkStartConditions() {
        if (ContextCompat.checkSelfPermission(requireContext().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != 0 ||
                ContextCompat.checkSelfPermission(getContext().getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != 0) {
            ActivityCompat.requestPermissions(requireActivity(),    // onRequestPermissionsResult()へ
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_LOCATION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_LOCATION) {
            if (ContextCompat.checkSelfPermission(requireContext().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != 0 ||
                    ContextCompat.checkSelfPermission(getContext().getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != 0) {
                ActivityCompat.requestPermissions(requireActivity(),    // onRequestPermissionsResult()へ
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_LOCATION);
            }
        }
    }


    ListFragmentDialog dialog;

    private void showConnectDialog() {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(ListFragmentDialog.KEY_CONTENT_LIST, mDeviceLists);
        if (dialog == null) {
            dialog = new ListFragmentDialog();
            dialog.setArguments(bundle);
            assert getFragmentManager() != null;
            dialog.show(getFragmentManager(), "");
            dialog.setOnSelectListener(new ListFragmentDialog.SelectListener() {
                @Override
                public void Select(NQDeviceBase deviceBase) {
                    NQBtDevice device = (NQBtDevice) deviceBase;
                    LogUtils.i(device.name);
                    if (!TextUtils.isEmpty(device.mac)) {
                        PenCtrlSdkManager.getInstance().connect(device);
                    }
                }

                @Override
                public void freshDevice() {
                    searchDevices();
                }
            });
        } else {
            dialog.setArguments(bundle);
            assert getFragmentManager() != null;
            dialog.show(getFragmentManager(), "");
        }
    }

    private void searchDevices() {
        Log.i(TAG, "searchDevices: 调用开始寻找设备");
        PenCtrlSdkManager.getInstance().startScanDevice();

    }


    private void addDevice(NQDeviceBase device) {
        //避免重复添加.

        NQBtDevice btDevice = (NQBtDevice) device;
        for (NQDeviceBase d : mDeviceLists) {
            NQBtDevice dDevice = (NQBtDevice) d;
            Log.i(TAG, "addDevice: " + dDevice.mac + " " + Thread.currentThread());
            if (dDevice.mac.equals(btDevice.mac)) {
                return;
            }
        }
        mDeviceLists.add(device);
        if (dialog != null) {
            dialog.addDeviceData(device);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //释放连接
        mDeviceLists.clear();
        PenCtrlSdkManager.getInstance().release();
        mBinding = null;
        LogUtils.d("MainActivity Destroy");
    }
}